import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:xuance/bean/PublicKeyBean.dart';
import 'package:xuance/bean/UserBean.dart';

class CacheUtil {
  static setToken(token) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    if (token == null) {
      await prefs.remove("token");
    } else {
      await prefs.setString("token", token);
    }
  }

  static Future<String> getToken() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.getString("token") ?? '';
  }

  static Future<PublicKeyBean?> getPubKey() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String? originStr = await prefs.getString("publicKey");
    if (originStr != null) {
      return PublicKeyBean.fromJson(jsonDecode(originStr));
    }
    return null;
  }

  static Future setPubKey(PublicKeyBean? pubKey) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    if (pubKey == null) {
      await prefs.remove("publicKey");
    } else {
      await prefs.setString("publicKey", jsonEncode(pubKey.toJson()));
    }
  }

  static setUser(UserBean? user) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    if (user == null) {
      await prefs.remove("user");
    } else {
      await prefs.setString("user", jsonEncode(user.toJson()));
    }
  }

  static Future<UserBean?> getUser() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String? originStr = await prefs.getString("user");
    if (originStr != null) {
      return UserBean.fromJson(jsonDecode(originStr));
    }
    return null;
  }
}
